from flask import Blueprint, request
from app.utils.response import success_response, error_response, paginated_response
from app.models.user import User  # 假设用户模型已定义

user_bp = Blueprint('user', __name__, url_prefix='/api/users')

@user_bp.route('', methods=['POST'])
def create_user():
    """
    新增用户
    """
    data = request.get_json()
    if not data or 'username' not in data or 'email' not in data:
        return error_response("用户名和邮箱为必填项", 400)

    try:
        user = User(username=data['username'], email=data['email'])
        user.save()  # 假设模型有 save 方法
        return success_response(user.to_dict(), "用户创建成功", 201)
    except Exception as e:
        return error_response(str(e), 500)

@user_bp.route('', methods=['GET'])
def get_users():
    """
    获取用户列表
    """
    try:
        page = request.args.get('page', default=1, type=int)
        per_page = request.args.get('per_page', default=20, type=int)
        users = User.query.paginate(page=page, per_page=per_page)  # 假设使用 SQLAlchemy
        users_list = [user.to_dict() for user in users.items]
        total = users.total

        return paginated_response(data=users_list, total=total,page=page, per_page=per_page)
    except Exception as e:
        return error_response(str(e), 500)

@user_bp.route('/<int:user_id>', methods=['GET'])
def get_user(user_id):
    """
    获取单个用户信息
    """
    try:
        user = User.query.get(user_id)
        if not user:
            return error_response("用户不存在", 404)
        return success_response(user.to_dict(), "用户信息获取成功")
    except Exception as e:
        return error_response(str(e), 500)

@user_bp.route('/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    """
    更新用户信息
    """
    data = request.get_json()
    if not data:
        return error_response("请求数据为空", 400)

    try:
        user = User.query.get(user_id)
        if not user:
            return error_response("用户不存在", 404)

        if 'username' in data:
            user.username = data['username']
        if 'email' in data:
            user.email = data['email']
        user.save()
        return success_response(user.to_dict(), "用户信息更新成功")
    except Exception as e:
        return error_response(str(e), 500)

@user_bp.route('/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    """
    删除用户
    """
    try:
        user = User.query.get(user_id)
        if not user:
            return error_response("用户不存在", 404)

        user.delete()  # 假设模型有 delete 方法
        return success_response(None, "用户删除成功")
    except Exception as e:
        return error_response(str(e), 500)